package org.eclipse.pde.toolbox.adaptors.internal;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IContributor;
import org.eclipse.core.runtime.IExtension;

public class NamespaceParent implements ITreeNode {

	private PluginFactory[] children;

	private IContributor contributor;
	private final Set ch;

	public NamespaceParent(IContributor key, Collection value) {
		// TODO Auto-generated constructor stub
		this.contributor = key;
		this.ch = new HashSet(value);
	}

	@Override
	public ITreeNode getParent() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean hasChildren() {
		// TODO Auto-generated method stub
		ITreeNode[] dsa = getChildren();
		return (dsa.length > 0);
	}

	@Override
	public ITreeNode[] getChildren() {
		// TODO Auto-generated method stub

		Map fct = new HashMap();

		for (Iterator it = ch.iterator(); it.hasNext();) {
			IExtension extension = (IExtension) it.next();
			IConfigurationElement[] factory = extension
					.getConfigurationElements();

			for (int i = 0; i < factory.length; i++) {

				if (factory[i].getName().equalsIgnoreCase("factory")) {
					String factoryName = factory[i]
							.getAttribute("adaptableType");
					IConfigurationElement[] adapters = factory[i].getChildren();

					Set tip = (Set) fct.get(factoryName);
					if (tip == null) {
						tip = new HashSet();
						fct.put(factoryName, tip);
					}

					for (int j = 0; j < adapters.length; j++) {
						String adapterName = adapters[j].getAttribute("type");
						tip.add(adapterName);

					}
				}
			}
		}

		Set set = fct.entrySet();
		children = new PluginFactory[set.size()];
		int k = 0;
		for (Iterator it = set.iterator(); it.hasNext();) {
			Map.Entry e = (Map.Entry) it.next();
			children[k] = new PluginFactory((String) e.getKey(), this,(Set) e.getValue());
			k++;

		}

		return children;
	}

	public String toString() {

		return contributor.getName();

	}

	@Override
	public String getDescription() {
		// TODO Auto-generated method stub
		return contributor.getName();
	}
	

}
